package com.waypolice.manager.service.impl;

import com.waypolice.common.pojo.TaotaoResult;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.manager.service.ArcCreateService;
import com.waypolice.manager.service.MainMenuService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.mapper.*;
import com.waypolice.mapper.handwriting.CmsJudItemMapperSon;
import com.waypolice.mapper.handwriting.CmsJudVolumeMapperSon;
import com.waypolice.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 档案著录实现类
 * @author zry
 *
 */
@Service
public class ArcCreateServiceImpl implements ArcCreateService{
	@Autowired
	private CmsJudVolumeMapper cmsJudVolumeMapper;
    @Autowired
	private CmsJudVolumeMapperSon cmsJudVolumeMapperSon;
	@Autowired
	private CmsJudItemMapperSon cmsJudItemMapperSon;
	@Autowired
	private CmsJudItemMapper cmsJudItemMapper;
	@Autowired
	private VolAndItemService volAndItemService;

	@Override
	public TaotaoResult inserJudVolMessage(String volItemNumber,String volCarrier,String volPublicStatus,String vol_class, String vol_storagetime, String vol_no, String vol_fian, String vol_title, String vol_arcyear, String vol_arcunit, String vol_auditleader, String vol_auditdate,
										   String vol_insidedate, String vol_secret, String secretDateline,String vol_total, String vol_current, String vol_totalpage, String vol_desc) {
		TaotaoResult result =new TaotaoResult();
		CmsJudVolume cmsJudVolume = new CmsJudVolume();
		cmsJudVolume.setVolClass(vol_class);
		cmsJudVolume.setVolStorageTime(vol_storagetime);
		cmsJudVolume.setVolNo(vol_no);
		cmsJudVolume.setVolFian(vol_fian);
		cmsJudVolume.setVolTitle(vol_title);
		cmsJudVolume.setVolArchiveYear(vol_arcyear);
		cmsJudVolume.setVolArchiveUnit(vol_arcunit);
		cmsJudVolume.setVolAuditLeader(vol_auditleader);
		cmsJudVolume.setVolAuditDate(vol_auditdate);
		cmsJudVolume.setVolInsideDate(vol_insidedate);
		cmsJudVolume.setVolSecret(vol_secret);
		cmsJudVolume.setVolStr3(secretDateline);
		cmsJudVolume.setVolTotal(vol_total);
		cmsJudVolume.setVolCurrent(vol_current);
		cmsJudVolume.setVolTotalPage(vol_totalpage);
		cmsJudVolume.setVolDesc(vol_desc);
		cmsJudVolume.setVolPublicStatus(Integer.valueOf(volPublicStatus));
		cmsJudVolume.setVolCarrier(volCarrier);
		cmsJudVolume.setVolItemNumber(volItemNumber);
		long i = cmsJudVolumeMapperSon.insertJudReturnId(cmsJudVolume);
		if(i != 1){
			result.setStatus(101);
		}else{
			Long volId = cmsJudVolume.getVolId();
			result.setMsg(volId.toString());
			result.setStatus(200);
		}
		return result;
	}

	@Override
	public TaotaoResult inserJudItemMessage(String itemStr5,String volId, String itemNumber, String itemPageNumber, String partNumber, String itemStartDate, String itemTitle, String itemFileNumber, String itemSecretLevel, String itemSecretDateline,String dutyPerson) {
		TaotaoResult result =new TaotaoResult();
		CmsJudItem cmsJudItem = new CmsJudItem();
		cmsJudItem.setItmeVolId(Long.valueOf(volId));
		Long itemnum = null;
		if(!StringUtils.isBlank(itemNumber)){
			itemnum = Long.valueOf(itemNumber);
		}
		cmsJudItem.setItemNum(itemnum);
		cmsJudItem.setItemName(itemFileNumber);
		cmsJudItem.setItemTemporary(partNumber);
		cmsJudItem.setItemSecret(itemSecretLevel);
		cmsJudItem.setItemStr6(itemSecretDateline);
		cmsJudItem.setItemTitle(itemTitle);
		cmsJudItem.setItemRespons(dutyPerson);
		cmsJudItem.setItemCreateTime(itemStartDate);
		cmsJudItem.setItemStr5(itemStr5);
		Long itemPageNum = null;
		if(!StringUtils.isBlank(itemPageNumber)){
			itemPageNum = Long.valueOf(itemPageNumber);
		}
		cmsJudItem.setItemPage(itemPageNum);
		long i =  cmsJudItemMapperSon.insertItemReturnId(cmsJudItem);
		if(i != 1){
			result.setStatus(101);
		}else{
			Long itemId = cmsJudItem.getItemId();
			Long itmeVolId = cmsJudItem.getItmeVolId();
			CmsJudItemExample example = new CmsJudItemExample();
			CmsJudItemExample.Criteria criteria = example.createCriteria();
			criteria.andItmeVolIdEqualTo(itmeVolId);
			List<CmsJudItem> items = cmsJudItemMapper.selectByExample(example);
			//总件数
			int itemNum = items.size();
			CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(itmeVolId);
			cmsJudVolume.setVolItemNumber(String.valueOf(itemNum));
			cmsJudVolumeMapper.updateByPrimaryKeySelective(cmsJudVolume);
			result.setMsg(itemId.toString());
			result.setStatus(200);
		}
		return result;
	}

	@Override
	public List<CmsJudItem> findItemLists(Long volId) {
		CmsJudItemExample example = new CmsJudItemExample();
		CmsJudItemExample.Criteria criteria = example.createCriteria();
		criteria.andItmeVolIdEqualTo(volId);
		List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(example);
		return cmsJudItems;
	}

	@Override
	public TaotaoResult updateJudVolMessage(String volItemNumber,String volCarrier,String volPublicStatus,String volId, String vol_class, String vol_storagetime, String vol_no, String vol_fian, String vol_title, String vol_arcyear, String vol_arcunit, String vol_auditleader, String vol_auditdate, String vol_insidedate, String vol_secret, String secretDateline,String vol_total, String vol_current, String vol_totalpage, String vol_desc) {
		TaotaoResult result = new TaotaoResult();
		CmsJudVolumeExample example = new CmsJudVolumeExample();
		CmsJudVolumeExample.Criteria criteria = example.createCriteria();
		criteria.andVolIdEqualTo(Long.valueOf(volId));
		List<CmsJudVolume> cmsJudVolumes = cmsJudVolumeMapper.selectByExample(example);
		CmsJudVolume cmsJudVolume = cmsJudVolumes.get(0);
		cmsJudVolume.setVolClass(vol_class);
		cmsJudVolume.setVolStorageTime(vol_storagetime);
		cmsJudVolume.setVolNo(vol_no);
		cmsJudVolume.setVolFian(vol_fian);
		cmsJudVolume.setVolTitle(vol_title);
		cmsJudVolume.setVolArchiveYear(vol_arcyear);
		cmsJudVolume.setVolArchiveUnit(vol_arcunit);
		cmsJudVolume.setVolAuditLeader(vol_auditleader);
		cmsJudVolume.setVolAuditDate(vol_auditdate);
		cmsJudVolume.setVolInsideDate(vol_insidedate);
		cmsJudVolume.setVolSecret(vol_secret);
		cmsJudVolume.setVolStr3(secretDateline);
		cmsJudVolume.setVolTotal(vol_total);
		cmsJudVolume.setVolCurrent(vol_current);
		cmsJudVolume.setVolTotalPage(vol_totalpage);
		cmsJudVolume.setVolDesc(vol_desc);
		cmsJudVolume.setVolEditDate(DateTimeUtil.getNow());
		cmsJudVolume.setVolPublicStatus(Integer.valueOf(volPublicStatus));
		cmsJudVolume.setVolCarrier(volCarrier);
		cmsJudVolume.setVolItemNumber(volItemNumber);
		int i = cmsJudVolumeMapper.updateByPrimaryKeySelective(cmsJudVolume);
		if(i != 1){
			result.setStatus(101);
		}else{
			result.setMsg(volId.toString());
			result.setStatus(200);

			//修改卷的公开状态时，该卷下所有的件进行变更
			CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
			CmsJudItemExample.Criteria criteriaWR = cmsJudItemExample.createCriteria();
			criteriaWR.andItmeVolIdEqualTo(Long.valueOf(volId));
			List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
			for (CmsJudItem cmsJudItem : cmsJudItems) {
				cmsJudItem.setItemStr5(volPublicStatus);
				int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
			}
		}
		return result;
	}

	@Override
	public TaotaoResult updateJudItemMessage(String itemStr5,String itemId, String volId, String itemNumber, String itemPageNumber, String partNumber, String itemStartDate, String itemTitle, String itemFileNumber, String itemSecretLevel,String itemSecretDateline, String dutyPerson) {
		TaotaoResult result = new TaotaoResult();
		CmsJudItemExample example = new CmsJudItemExample();
		CmsJudItemExample.Criteria criteria = example.createCriteria();
		criteria.andItemIdEqualTo(Long.valueOf(itemId));
		List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(example);
		CmsJudItem cmsJudItem = cmsJudItems.get(0);
		cmsJudItem.setItmeVolId(Long.valueOf(volId));
		Long itemnum = null;
		if(!StringUtils.isBlank(itemNumber)){
			itemnum = Long.valueOf(itemNumber);
		}
		cmsJudItem.setItemNum(itemnum);
		cmsJudItem.setItemName(itemFileNumber);
		cmsJudItem.setItemTemporary(partNumber);
		cmsJudItem.setItemSecret(itemSecretLevel);
		cmsJudItem.setItemStr6(itemSecretDateline);
		cmsJudItem.setItemTitle(itemTitle);
		cmsJudItem.setItemRespons(dutyPerson);
		cmsJudItem.setItemStr5(itemStr5);
		cmsJudItem.setItemCreateTime(itemStartDate);
		Long itemPageNum = null;
		if(!StringUtils.isBlank(itemPageNumber)){
			itemPageNum = Long.valueOf(itemPageNumber);
		}
		cmsJudItem.setItemPage(itemPageNum);
		cmsJudItem.setItemEditDate(DateTimeUtil.getNow());
		int i = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
		if(i != 1){
			result.setStatus(101);
		}else{
			result.setMsg(itemId.toString());
			result.setStatus(200);
		}
		return result;
	}

	@Override
	public CmsJudItem selectCmsJudItemByItemId(Long itemId) {
		CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(itemId);
		return cmsJudItem;
	}

	@Override
	public TaotaoResult findSameArcNumber(String volId,String arcNumber) {
		TaotaoResult result = new TaotaoResult();
		CmsJudVolumeExample example = new CmsJudVolumeExample();
		CmsJudVolumeExample.Criteria criteria = example.createCriteria();
		criteria.andVolNoEqualTo(arcNumber);
		List<CmsJudVolume> cmsJudVolumes = cmsJudVolumeMapper.selectByExample(example);
		if(!cmsJudVolumes.isEmpty()) {
		    //存在该案卷号
            for (CmsJudVolume cmsJudVolume : cmsJudVolumes) {
                if (!volId.equals(cmsJudVolume.getVolId().toString())) {
                    result.setStatus(101);
                    return result;
                }
            }
        }
        result.setStatus(200);
		return result;
	}

	@Override
	public TaotaoResult findItemNumberIsRepeat(String itemNumber,String volId) {
		TaotaoResult taotaoResult = new TaotaoResult();
		CmsJudItemExample example = new CmsJudItemExample();
		CmsJudItemExample.Criteria criteria = example.createCriteria();
		criteria.andItmeVolIdEqualTo(Long.valueOf(volId));
		List<CmsJudItem> list = cmsJudItemMapper.selectByExample(example);
		for (CmsJudItem cmsJudItem:list){
			Long itemNum = cmsJudItem.getItemNum();
			Long aLong = Long.valueOf(itemNumber);
			if(	itemNum.equals(aLong)){
				taotaoResult.setStatus(101);
				return taotaoResult;
			}
		}
		taotaoResult.setStatus(200);
		return taotaoResult;
	}

	@Override
	public TaotaoResult deleteItemMessage(String itemId, String type) throws Exception {
		TaotaoResult result = new TaotaoResult();
		CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
		String itemStr2 = cmsJudItem.getItemStr2();
		int i = cmsJudItemMapper.deleteByPrimaryKey(Long.valueOf(itemId));
		if("1".equals(type)){
			FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
			fastDFSClient.deleteFile(itemStr2);
		}
		if(i == 1){
			result.setStatus(200);
		}else{
			result.setStatus(101);
		}
		return result;
	}

	@Override
	public long selectMaxItemNumber(String volId) {
		long l = cmsJudItemMapperSon.selectMaxItemNum(Long.valueOf(volId));
		return l;
	}

	@Override
	public TaotaoResult findSameItemPage(String itemId, String volId, String itemPageNumber) {
		TaotaoResult result = new TaotaoResult();
		CmsJudItemExample example = new CmsJudItemExample();
		CmsJudItemExample.Criteria criteria = example.createCriteria();
		criteria.andItmeVolIdEqualTo(Long.valueOf(volId));
		List<CmsJudItem> list = cmsJudItemMapper.selectByExample(example);
		for (CmsJudItem cmsJudItem:list) {
			if(StringUtils.isBlank(itemId)){
				//新加件
				if(itemPageNumber.equals(cmsJudItem.getItemPage().toString())){
					//页次相同
					result.setStatus(101);
					return result;
				}
			}else{
				//修改件
				if(itemPageNumber.equals(cmsJudItem.getItemPage().toString())){
					if(!itemId.equals(cmsJudItem.getItemId().toString())){
						//不同件
						result.setStatus(101);
						return result;
					}
				}
			}
		}
		result.setStatus(200);
		return result;
	}
	/**
	 * 已归档的档案，重新归档卷
	 *
	 * @return user
	 */
	@Override
	public TaotaoResult submitJudVolMessageAndArchive(String volItemNumber,String volCarrier,String volPublicStatus,String volId, String vol_class, String vol_storagetime, String vol_no, String vol_fian, String vol_title, String vol_arcyear, String vol_arcunit, String vol_auditleader, String vol_auditdate, String vol_insidedate, String vol_secret, String secretDateline, String vol_total, String vol_current, String vol_totalpage, String vol_desc) {
		TaotaoResult finalresult = new TaotaoResult();
		TaotaoResult result = updateJudVolMessage(volItemNumber,volCarrier,volPublicStatus,volId, vol_class, vol_storagetime, vol_no, vol_fian, vol_title, vol_arcyear, vol_arcunit, vol_auditleader, vol_auditdate, vol_insidedate, vol_secret, secretDateline, vol_total, vol_current, vol_totalpage, vol_desc);
		if(result.getStatus() == 200){
			//更新完卷信息
			String msg = result.getMsg();
			CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(msg));
			List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(cmsJudVolume.getVolId(), 2);
			//添加件数
			cmsJudVolume.setVolItemNumber(String.valueOf(cmsJudIt.size()));
			//生成档号
			String fileNumber = null;
			try {
				fileNumber = volAndItemService.getFileNumber(cmsJudVolume);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if("error".equals(fileNumber) || org.apache.commons.lang3.StringUtils.isBlank(fileNumber)){
				finalresult.setStatus(102);
				finalresult.setMsg("构成档号的字段不能为空!");
				return finalresult;
			}
			cmsJudVolume.setVolCaseNum(fileNumber);
			int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume);
			if(i != 1){
				finalresult.setStatus(100);
				finalresult.setMsg("更新卷信息失败!");
				return finalresult;
			}else{
				//添加件号
				List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(Long.valueOf(msg),2);
				for (CmsJudItem cmsJudItem : cmsJudItems) {
					String str = String.format("%04d", cmsJudItem.getItemPage());
					cmsJudItem.setItemStr1(fileNumber+"-"+str);
					cmsJudItem.setItemStr11Date(DateTimeUtil.getNow());
					int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
				}
			}
		}else{
			finalresult.setStatus(100);
			finalresult.setMsg("更新卷信息失败!");
			return finalresult;
		}
		finalresult.setMsg(volId);
		finalresult.setStatus(200);
		return finalresult;
	}
	/**
	 * 已归档的档案，重新归档件
	 *
	 */
	@Override
	public TaotaoResult submitJudItemMessageArchive(String itemStr5,String itemId, String volId, String itemNumber, String itemPageNumber, String partNumber, String itemStartDate, String itemTitle, String itemFileNumber, String itemSecretLevel, String itemSecretDateline, String dutyPerson) {
		TaotaoResult finalResult = new TaotaoResult();
		//1:查询卷、件信息
		CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
		//2：根据件信息更新件
		TaotaoResult result = updateJudItemMessage(itemStr5,itemId, volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel, itemSecretDateline, dutyPerson);
		if(result.getStatus() == 200){
			String msg = result.getMsg();
			CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(msg));
			//更新件信息成功,重新生成件号
			String fileNumber = cmsJudVolume.getVolCaseNum();
			String str = String.format("%04d", cmsJudItem.getItemPage());
			cmsJudItem.setItemStr1(fileNumber+"-"+str);
			cmsJudItem.setItemStr11Date(DateTimeUtil.getNow());
			int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
			if(i1 != 1){
				finalResult.setStatus(100);
				finalResult.setMsg("更新件信息失败!");
				return finalResult;
			}
		}else{
			finalResult.setStatus(100);
			finalResult.setMsg("更新件信息失败!");
			return finalResult;
		}
		finalResult.setMsg(result.getMsg());
		finalResult.setStatus(200);
		return finalResult;
	}
	/**
	 * 已归档的档案，添加新件
	 *
	 */
	@Override
	public TaotaoResult submitInsertJudItemMessageArchive(String itemStr5,String volId, String itemNumber, String itemPageNumber, String partNumber, String itemStartDate, String itemTitle, String itemFileNumber, String itemSecretLevel, String itemSecretDateline, String dutyPerson) {
		TaotaoResult finalResult = new TaotaoResult();
		CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
		//第一步先插入新件
		TaotaoResult result = inserJudItemMessage(itemStr5,volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel, itemSecretDateline, dutyPerson);
		if(result.getStatus() == 200){
			String msg = result.getMsg();
			CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(msg));
			//第二步插入成功，添加件号
			String fileNumber = cmsJudVolume.getVolCaseNum();
			String str = String.format("%04d", cmsJudItem.getItemPage());
			cmsJudItem.setItemStr1(fileNumber+"-"+str);
			cmsJudItem.setItemStr11Date(DateTimeUtil.getNow());
			int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
			if(i1 != 1){
				finalResult.setStatus(100);
				finalResult.setMsg("添加件信息失败!");
				return finalResult;
			}else{
				//第三步，更改卷的件数
				List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(cmsJudVolume.getVolId(), 2);
				cmsJudVolume.setVolItemNumber(String.valueOf(cmsJudIt.size()));
				cmsJudVolume.setVolEditDate(DateTimeUtil.getNow());
				int i = cmsJudVolumeMapper.updateByPrimaryKeySelective(cmsJudVolume);
				if(i1 != 1){
					finalResult.setStatus(100);
					finalResult.setMsg("添加件信息失败!");
					return finalResult;
				}
			}
		}
		finalResult.setMsg(result.getMsg());
		finalResult.setStatus(200);
		return finalResult;
	}
}
